
package com.platform.modules.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.mall.entity.MallTemplateEntity;
import com.platform.modules.mall.service.MallTemplateService;
import com.platform.modules.sms.SmsSend;
import com.platform.modules.sms.entitys.SmsTemplateEntity;
import com.platform.modules.sys.dao.SysSmsLogDao;
import com.platform.modules.sys.entity.SmsConfig;
import com.platform.modules.sys.entity.SysSmsLogEntity;
import com.platform.modules.sys.service.SysConfigService;
import com.platform.modules.sys.service.SysSmsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 短信发送日志Service实现类
 *
 * @author
 * @date 2019-02-12 09:51:15
 */
@Service("sysSmsLogService")
public class SysSmsLogServiceImpl extends ServiceImpl<SysSmsLogDao, SysSmsLogEntity> implements SysSmsLogService {

    @Autowired
    private SysConfigService sysConfigService;
    @Resource
    private JedisUtil jedisUtil;
    @Resource
    MallTemplateService templateService;

    @Value("${ali.codeTemplateId}")
    private String templateId;

    @Override
    public List<SysSmsLogEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.STIME");
        params.put("asc", false);
        Page<SysSmsLogEntity> page = new Query<SysSmsLogEntity>(params).getPage();
        return page.setRecords(baseMapper.selectSysSmsLogPage(page, params));
    }

    @Override
    public void add(SysSmsLogEntity sysSmsLog) {
        this.save(sysSmsLog);
    }

    @Override
    public void update(SysSmsLogEntity sysSmsLog) {
        this.update(sysSmsLog, new QueryWrapper<>());
    }

    @Override
    public void delete(String id) {
        this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(String[] ids) {
        this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public SysSmsLogEntity sendSms(String userId, SysSmsLogEntity smsLog) {
        return sendSms(userId, smsLog, templateId);
    }

    public SysSmsLogEntity sendSms(String userId, SysSmsLogEntity smsLog, Object params) {
        //获取云存储配置信息
        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
        JSONObject configObject = sysConfigService.getConfigObject(Constant.SYS_PROXY_SERVER, JSONObject.class);
        try {
            log.debug(JSONObject.toJSON(smsLog).toString());
            if (config.getType() == 1) {
                if (StringUtils.isNullOrEmpty(config)) {
                    throw new BusinessException("请先配置短信平台信息");
                }
                if (StringUtils.isNullOrEmpty(config.getSecretId())) {
                    throw new BusinessException("请先配置短信平台APPID");
                }
                if (StringUtils.isNullOrEmpty(config.getAppid())) {
                    throw new BusinessException("请先配置短信平台APPID");
                }
                if (StringUtils.isNullOrEmpty(config.getSecretKey())) {
                    throw new BusinessException("请先配置短信APP_KEY");
                }
                if (StringUtils.isNullOrEmpty(config.getSign())) {
                    throw new BusinessException("请先配置短信平台签名");
                }
                throw new BusinessException("未实现的发送方式");
//                SendSmsResponse result;
//                result = SmsUtil.sendSms(config.getSecretId(), config.getSecretKey(), config.getAppid(), templateID, smsLog.getMobile().split(","), smsLog.getContent().split(Constant.SPLICING_SYMBOL));
            } else if (config.getType() == 2) {
                if (StringUtils.isNullOrEmpty(config.getAccessKeyId())) {
                    throw new BusinessException("请先配置阿里云AccessKeyId");
                }
                if (StringUtils.isNullOrEmpty(config.getSecret())) {
                    throw new BusinessException("请先配置阿里云secret");
                }
                if (StringUtils.isNullOrEmpty(config.getSign())) {
                    throw new BusinessException("请先配置短信平台签名");
                }
                Boolean isEnable = false;
                String proxyIp = null;
                String proxyPort = null;
                if (configObject != null) {
                    isEnable = configObject.getBoolean("isEnable");
                    if (isEnable == null) {
                        isEnable = false;
                    }
                    proxyIp = configObject.getString("proxyServerIp");
                    proxyPort = configObject.getString("proxyPort");
                }
                if (!(params instanceof String)) {
                    throw new BusinessException("模板参数错误！");
                }
                String result = AliyunSmsUtils.sendSms(config.getAccessKeyId(), config.getSecret(), smsLog.getMobile(),
                        smsLog.getContent(), (String) params, config.getSign(), isEnable, proxyIp, proxyPort);
                JSONObject js = JSONObject.parseObject(result);
                log.debug(js.toString());
                smsLog.setSendStatus("OK".equals(js.getString("Code")) ? 0 : 1);
                //发送成功
                smsLog.setSendId(js.getString("BizId"));
                smsLog.setSuccessNum(1);
                smsLog.setReturnMsg(js.getString("Message"));
                smsLog.setUserId(userId);
                smsLog.setSign(config.getSign());
                smsLog.setStime(new Date());
                smsLog.setRequestId(js.getString("RequestId"));
                smsLog.setId(null);
                //保存发送记录
                save(smsLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return smsLog;
    }

    @Override
    public void sendSms(SmsSend smsSend) {
        SysSmsLogEntity entity = new SysSmsLogEntity();
        entity.setContent(smsSend.content);
        entity.setMobile(smsSend.phone);
        entity.setCode(smsSend.code);
        sendSms(smsSend.userId, entity, smsSend.params);
    }

    @Override
    public SmsSend build(String phone, String userId, Object params) {
        return new SmsSend(this, phone, jedisUtil, userId, params);
    }

    @Override
    public SmsTemplateEntity getTemplate(String configId) {
        MallTemplateEntity templateEntity = jedisUtil.getCache("SmsTemplate:" + configId,
                () -> templateService.selectMallTemplate(1, configId),
                MallTemplateEntity.class);
        if(templateEntity == null){
            throw new BusinessException("模板ID错误！");
        }
        SmsTemplateEntity entity = new SmsTemplateEntity();
        entity.setContent(templateEntity.getTemplateData());
        entity.setParams(templateEntity.getTemplateId());
        return entity;
    }
}
